<!--
 * @Description: 添加组件，蒙层对话框
 * @Author: youzi
 * @Date: 2020-05-20 14:11:14
 * @LastEditors: youzi
 * @LastEditTime: 2020-10-21 10:57:47
-->
<template>
  <modal
    :visible="visible"
    :title="addOrEdit === 0 ? '新增' : '编辑'"
    okText="保存"
    @cancelHandler="onClose"
    @okHandler="handleSubmit"
    :destroyOnClose="true"
    :width="600"
    :bodyHeight="0.8"
    :loading="loading"
  >
    <template slot="content">
      <a-spin :spinning="loading" :delay="200" tip="提交中...">
        <a-form :form="form">
          <a-form-item label="标题" v-bind="formItemLayout">
            <a-input
              v-decorator="[
                'title',
                { rules: [{ required: true, message: '标题不能为空' }, { max: 50, message: '字数不能超过50字' }], initialValue: initRecord.title }
              ]"
              placeholder="请输入标题"
            />
          </a-form-item>
          <a-form-item label="内容" v-bind="formItemLayout">
            <a-input
              v-decorator="[
                'content',
                { rules: [{ required: true, message: '内容不能为空' }, { max: 50, message: '字数不能超过50字' }], initialValue: initRecord.content }
              ]"
              placeholder="请输入内容"
            />
          </a-form-item>
          <a-form-item label="状态" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="[`stat`, { rules: [{ required: true, message: '请选择状态' }], initialValue: initRecord.stat }]"
              placeholder="请选择状态"
              :options="statusItems"
            >
            </a-select>
          </a-form-item>
          <a-form-item
            v-bind="formItemLayout"
            v-for="(item, index) in renderImageData"
            :key="index + 'image'"
            :label="item.inputTitle"
            :extra="item.extra"
          >
<!--            @preview="handleImagePreview"-->
            <a-upload
              :multiple="false"
              :accept="item.accept"
              :fileList="item.fileList"
              list-type="picture-card"
              :beforeUpload="beforeImageUpload"
              @change="handleImageChange(item.dataIndex, index, $event)"
              v-decorator="[
                `${item.dataIndex}`,
                {
                  rules: [
                    { required: item.required, message: `${item.inputTitle}不能为空` },
                    {
                      validator: (rule, val, callback) =>
                        handleImageValidate(rule, val, callback, item.inputTitle, item.required)
                    }
                  ],
                  validateTrigger: ['change'],
                  initialValue: initRecord.image
                }
              ]"
            >
              <a-button icon="upload" v-if="item.fileList.length == 0">上传</a-button>
            </a-upload>
          </a-form-item>
        </a-form>
      </a-spin>
    </template>
  </modal>
</template>
<script>
import modal from '~/tool/modal';
import { fileOperationWithRenderImageData } from '@/mixin/image-operation';
import { regexp } from 'utils/common';

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 12 }
};

const renderImageData = [
  {
    inputTitle: '图片',
    dataIndex: 'image',
    required: true,
    accept: '.png, .jpg, .jpeg',
    extra: '（仅支持上传.png, .jpg, .jpeg格式，图片大小：710*360）',
    fileList: []
  }
];

export default {
  name: 'add',
  components: { modal },
  mixins: [fileOperationWithRenderImageData],
  props: {
    // 新增：0，编辑：1
    addOrEdit: {
      type: Number,
      default: 0
    },
    initRecord: {
      type: Object,
      default: () => ({})
    },
    // 状态
    statusItems: {
      type: Array,
      default: () => []
    },
    visible: {
      default: false
    },
    // 需要的api
    apiURL: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      regexp,
      renderImageData: JSON.parse(JSON.stringify(renderImageData)),
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this)
    };
  },
  methods: {
    /**
     * @desc: 渲染selection
     * @author: youzi
     */
    reset() {
      this.loading = false;
      this.renderImageData = JSON.parse(JSON.stringify(renderImageData));
      this.form.resetFields();
    },
    onClose() {
      this.$confirm({
        title: '确定放弃编辑吗？',
        content: '',
        okText: '确定',
        cancelText: '取消',
        onOk: this.onCloseConfirm
      });
    },
    onCloseConfirm() {
      this.reset();
      this.$emit('close');
    },
    handleSubmit() {
      // debugger;
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$confirm({
            title: '确定保存吗？',
            content: '',
            okText: '确定',
            cancelText: '取消',
            onOk: this.handleConfirmSubmit
          });
        }
      });
    },
    handleConfirmSubmit() {
      let that = this;
      this.loading = true;
      let tmpObj = this.form.getFieldsValue();
      that.renderImageData.forEach(el => {
        if (!!el.fileList.length) {
          let tmpList = [];
          el.fileList.forEach(file => {
            tmpList.push(file.url);
          });
          let tmpStr = tmpList.join(',');
          tmpObj[el.dataIndex] = tmpStr;
        }
      });
      console.log(tmpObj);
      let postUrl = this.addOrEdit === 0 ? this.apiURL.addRecords : this.apiURL.editRecords;
      if (that.addOrEdit !== 0) {
        tmpObj.id = that.initRecord.id;
      }
      that.$post(postUrl, {
        ...tmpObj
      })
        .then(r => {
          that.reset();
          that.$emit('success');
        })
        .catch(() => {
          that.loading = false;
        });
    }
  },
  mounted() {
    if (this.addOrEdit && this.visible) {
      this.renderImageList();
    }
  },
};
</script>
